'use client';

import React, { useState, useRef } from 'react';
import { ProTable, ActionType } from '@ant-design/pro-components';
import { Button, Space, Tag, Popconfirm, Select, Input, Modal, Form } from 'antd';
import { PlusOutlined, DeleteOutlined, UserOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import {  useRouter, useSearchParams } from 'next/navigation';
import { useMessage } from '@/hooks/useMessage';
import { instrumentApi } from '@/apis/instrument';
import { userApi, UserListResponse, UserPageParams } from '@/apis/user';
import {
  InstrumentTrainedUserResponse,
  InstrumentTrainedUserPageParams
} from '@/types/instrument';

// 可添加的用户类型 (使用API返回的用户数据)
type AvailableUser = UserListResponse;

const TrainingListPage: React.FC = () => {
  const router = useRouter();   
  const searchParams = useSearchParams();
  const actionRef = useRef<ActionType | null>(null);
  const message = useMessage();
  const [searchModalVisible, setSearchModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [searchKeyword, setSearchKeyword] = useState('');
  const [availableUsers, setAvailableUsers] = useState<AvailableUser[]>([]);
  const [selectedUsers, setSelectedUsers] = useState<number[]>([]);

  const instrumentId = parseInt(searchParams.get('id') as string);
  // 获取培训名单数据
  const fetchTrainingList = async (params: InstrumentTrainedUserPageParams & { current?: number; pageSize?: number }) => {
    try {
      const queryParams: InstrumentTrainedUserPageParams = {
        instrumentId,
        current: params.current,
        size: params.pageSize,
        searchKey: params.searchKey,
      };

      const response = await instrumentApi.getTrainedUserPage(queryParams);
      
      return {
        data: response.records,
        success: true,
        total: response.total,
      };
    } catch (error) {
      console.error('获取培训名单失败:', error);
      message.error('获取培训名单失败');
      return {
        data: [],
        success: false,
        total: 0,
      };
    }
  };

  // 搜索可添加的用户
  const searchAvailableUsers = async (keyword: string) => {
    try {
      const params: UserPageParams = {
        current: 1,
        size: 50, // 搜索时显示更多结果
        searchKey: keyword, // 根据关键词搜索
        status: 1, // 只搜索正常状态的用户
      };

      const response = await userApi.getUserPageList(params);
      setAvailableUsers(response.records);
    } catch (error) {
      console.error('搜索用户失败:', error);
      message.error('搜索用户失败');
      setAvailableUsers([]);
    }
  };

  // 添加用户到培训名单
  const handleAddUsers = async () => {
    if (selectedUsers.length === 0) {
      message.warning('请选择要添加的用户');
      return;
    }

    try {
      // 批量添加用户
      const promises = selectedUsers.map(userId => 
        instrumentApi.createTrainedUser({
          instrumentId,
          userId
        })
      );
      
      await Promise.all(promises);
      
      message.success(`成功添加 ${selectedUsers.length} 个用户到培训名单`);
      setSearchModalVisible(false);
      setSelectedUsers([]);
      setSearchKeyword('');
      setAvailableUsers([]);
      form.resetFields();
      actionRef.current?.reload();
    } catch (error) {
      console.error('添加用户失败:', error);
      message.error('添加用户失败');
    }
  };

  // 删除用户
  const handleDeleteUser = async (record: InstrumentTrainedUserResponse) => {
    try {
      await instrumentApi.deleteTrainedUser({
        id: record.id,
        tmbId: record.id // 根据实际API调整
      });
      
      message.success(`已将 ${record.name} 从培训名单中移除`);
      actionRef.current?.reload();
    } catch (error) {
      console.error('删除用户失败:', error);
      message.error('删除用户失败');
    }
  };

  // 批量删除用户
  const handleBatchDelete = async (userIds: React.Key[]) => {
    if (userIds.length === 0) {
      message.warning('请选择要删除的用户');
      return;
    }

    try {
      const promises = userIds.map(id => 
        instrumentApi.deleteTrainedUser({
          id: Number(id),
          tmbId: Number(id)
        })
      );
      
      await Promise.all(promises);
      
      message.success(`成功删除 ${userIds.length} 个用户`);
      actionRef.current?.reload();
    } catch (error) {
      console.error('批量删除用户失败:', error);
      message.error('批量删除用户失败');
    }
  };

  // 更新用户状态
  const handleUpdateUserStatus = async (userId: number, status: number) => {
    try {
      // TODO: 调用实际API更新用户状态
      console.log('更新用户状态:', { instrumentId, userId, status });
      
      message.success(`用户状态已更新为${status === 1 ? '正常' : '禁用'}`);
      actionRef.current?.reload();
    } catch (error) {
      console.error('更新用户状态失败:', error);
      message.error('更新用户状态失败');
    }
  };

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 120,
      render: (_: unknown, record: InstrumentTrainedUserResponse) => (
        <Space>
          <UserOutlined />
          {record.name}
        </Space>
      ),
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      width: 130,
    },
    {
      title: '用户ID',
      dataIndex: 'userId',
      key: 'userId',
      width: 100,
    },
    {
      title: '添加时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 160,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (_: unknown, record: InstrumentTrainedUserResponse) => (
        <Select
          value={record.status}
          size="small"
          style={{ width: 80 }}
          onChange={(value) => handleUpdateUserStatus(record.userId, value)}
        >
          <Select.Option value={1}>
            <Tag color="green">正常</Tag>
          </Select.Option>
          <Select.Option value={2}>
            <Tag color="red">禁用</Tag>
          </Select.Option>
        </Select>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (_: unknown, record: InstrumentTrainedUserResponse) => (
        <Space>
          <Popconfirm
            title="确认删除"
            description={`确定要将 ${record.name} 从培训名单中移除吗？`}
            onConfirm={() => handleDeleteUser(record)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer
      title="自主上机培训名单"
      extra={[
        <Button key="back" onClick={() => router.back()}>
          返回
        </Button>,
      ]}
    >
      <ProTable<InstrumentTrainedUserResponse>
        actionRef={actionRef}
        columns={columns}
        request={fetchTrainingList}
        rowKey="id"
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
        }}
        search={false}
        options={{
          reload: true,
          density: false,
          setting: false,
        }}
        toolBarRender={() => [
          <Button
            key="add"
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => setSearchModalVisible(true)}
            style={{ backgroundColor: '#69cac3', borderColor: '#69cac3' }}
          >
            添加用户
          </Button>,
        ]}
        tableAlertRender={({ selectedRowKeys }) => (
          <Space size={24}>
            <span>
              已选择 <a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a> 项
            </span>
          </Space>
        )}
        tableAlertOptionRender={({ selectedRowKeys }) => (
          <Space size={16}>
            <Popconfirm
              title="确认批量删除"
              description={`确定要删除选中的 ${selectedRowKeys.length} 个用户吗？`}
              onConfirm={() => handleBatchDelete(selectedRowKeys)}
              okText="确定"
              cancelText="取消"
            >
              <Button size="small" danger>
                批量删除
              </Button>
            </Popconfirm>
          </Space>
        )}
        rowSelection={{
          type: 'checkbox',
        }}
      />

      {/* 搜索添加用户弹窗 */}
      <Modal
        title="添加用户到培训名单"
        open={searchModalVisible}
        onCancel={() => {
          setSearchModalVisible(false);
          setSelectedUsers([]);
          setSearchKeyword('');
          setAvailableUsers([]);
          form.resetFields();
        }}
        onOk={handleAddUsers}
        width={800}
        okText="添加选中用户"
        cancelText="取消"
        okButtonProps={{
          disabled: selectedUsers.length === 0,
          style: { backgroundColor: '#69cac3', borderColor: '#69cac3' }
        }}
      >
        <Form form={form} layout="vertical">
          <Form.Item label="搜索用户" name="keyword">
            <Input.Search
              placeholder="请输入姓名、手机号或邮箱搜索用户"
              value={searchKeyword}
              onChange={(e) => setSearchKeyword(e.target.value)}
              onSearch={(value) => {
                if (value.trim()) {
                  searchAvailableUsers(value.trim());
                } else {
                  setAvailableUsers([]);
                }
              }}
              style={{ marginBottom: 16 }}
            />
          </Form.Item>
        </Form>

        {availableUsers.length > 0 && (
          <div>
            <div className="mb-3 text-sm text-gray-600">
              找到 {availableUsers.length} 个用户，请选择要添加的用户：
            </div>

            <ProTable<UserListResponse>
              dataSource={availableUsers}
              columns={[
                {
                  title: '姓名',
                  dataIndex: 'name',
                  width: 100,
                  render: (text) => (
                    <Space>
                      <UserOutlined />
                      {text}
                    </Space>
                  ),
                },
                {
                  title: '手机号',
                  dataIndex: 'phoneNumber',
                  width: 120,
                },
                {
                  title: '单位',
                  dataIndex: 'unit',
                  width: 120,
                  ellipsis: true,
                },
                {
                  title: '职位',
                  dataIndex: 'position',
                  width: 100,
                  ellipsis: true,
                },
                {
                  title: '状态',
                  dataIndex: 'status',
                  width: 80,
                  render: (status) => (
                    <Tag color={status === 1 ? 'green' : 'red'}>
                      {status === 1 ? '正常' : '禁用'}
                    </Tag>
                  ),
                },
              ]}
              rowKey="id"
              search={false}
              pagination={false}
              options={false}
              size="small"
              scroll={{ y: 300 }}
              rowSelection={{
                type: 'checkbox',
                selectedRowKeys: selectedUsers,
                onChange: (selectedRowKeys) => {
                  setSelectedUsers(selectedRowKeys as number[]);
                },
                getCheckboxProps: (record) => ({
                  disabled: record.status !== 1, // 禁用状态的用户不能选择
                }),
              }}
              tableAlertRender={({ selectedRowKeys }) => (
                <Space size={24}>
                  <span>
                    已选择 <a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a> 个用户
                  </span>
                </Space>
              )}
            />
          </div>
        )}

        {searchKeyword && availableUsers.length === 0 && (
          <div className="text-center py-8 text-gray-500">
            <UserOutlined style={{ fontSize: 24, marginBottom: 8 }} />
            <div>未找到匹配的用户</div>
          </div>
        )}
      </Modal>
    </PageContainer>
  );
};

export default TrainingListPage;